﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.BO;
using System.Data;
using System.Configuration;
using System.IO;

namespace PPAP.Web.SearchReport
{
    public partial class FilesSearch : PageBase
    {
       T_FileBO tbo = new T_FileBO ();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                btnSubmit_Click(null, null);
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");
            AspNetPager2.RecordCount = ds.Tables[0].Rows.Count;
            dgList.DataSource = GetPageTable(ds.Tables[0], AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            dgList.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        private DataSet GetDataSet(string sort)
        {
            string sql = " and 1=1 ";
            if (txtPPARNo.Text.Trim() != "")
                sql += " and lower('ppar-'||p.pparno||'.'||PPARVERSION) like lower('%" + txtPPARNo.Text.Trim() + "%') ";
            if (txtPartNo.Text.Trim() != "")
                sql += " and lower(r.bdntpartno) like lower('%" + txtPartNo.Text.Trim() + "%') ";
            if (txtPartName.Text.Trim() != "")
                sql += " and lower(r.bdntpartname) like lower('%" + txtPartName.Text.Trim() + "%') ";
            if (txtColor.Text.Trim() != "")
                sql += " and lower(r.color) like lower('%" + txtColor.Text.Trim() + "%') ";
            if (txtUser.Text.Trim() != "")
                sql += " and lower(t.upby) like lower('%" + txtUser.Text.Trim() + "%') ";
            if (txtStart.Text.Trim() != "")
                sql += " and trunc(t.uptime)>=to_date( '" + txtStart.Text.Trim() + "', 'yyyy-mm-dd ') ";
            if (txtEnd.Text.Trim() != "")
                sql += " and trunc(t.uptime)<=to_date( '" + txtEnd.Text.Trim() + "', 'yyyy-mm-dd ') ";
            if (DropDownList1.SelectedValue != "All")
                sql += " and t.filetype='" + DropDownList1.SelectedValue + "' ";
            sql += sort;
            DataSet ds = tbo.GetListForSearch(sql);
            return ds;
        }


        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }

        /// <summary>
        /// Export
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    r["d"] = r["isdelete"].ToString() == "1" ? "Yes" : "No";
                    r["d1"] = r["UpTime"].ToString() == "" ? r["UpTime"] : DateTime.Parse(r["UpTime"].ToString()).ToString("yyyy-MM-dd");
                }
                ds.Tables[0].Columns.Remove("UPTIME");
                ds.Tables[0].Columns.Remove("F_FILENAME");
                ds.Tables[0].Columns.Remove("ISDELETE");

                ds.Tables[0].Columns["ROWNUM"].ColumnName = "No.";
                ds.Tables[0].Columns["ATTACHMENTTYPE"].ColumnName = "Attach.type";
                ds.Tables[0].Columns["UPBY"].ColumnName = "Created by";
                ds.Tables[0].Columns["d1"].ColumnName = "Upload time";
                ds.Tables[0].Columns["PPARNO"].ColumnName = "PPAR No.";
                ds.Tables[0].Columns["BDNTPARTNO"].ColumnName = "Part No.";
                ds.Tables[0].Columns["FILETYPE"].ColumnName = "Type";
                ds.Tables[0].Columns["FILESIZE"].ColumnName = "Size";
                ds.Tables[0].Columns["D"].ColumnName = "IsDelete";
                ds.Tables[0].Columns["F_URL"].ColumnName = "Link";
                ds.Tables[0].Columns["bdntpartname"].ColumnName = "Part name";

                CreateExcel(ds, "FilesSearch");
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string GetLink(string filename)
        {
            //string filepath = "ftp://" + ConfigurationManager.AppSettings["ftpServerIP"] + "/";
            string filepath = ConfigurationManager.AppSettings["FilePath"];
            return filepath + filename;
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            if (File.Exists(ConfigurationManager.AppSettings["FilePath"] + link.ToolTip))
            {
                FileInfo file = new FileInfo(ConfigurationManager.AppSettings["FilePath"] + link.ToolTip);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码    
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
                AlertMessage("File does not exist");
        }

        protected void dgList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.dgList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.dgList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.dgList.Attributes["SortExpression"] = sortExpression;
            this.dgList.Attributes["SortDirection"] = sortDirection;


            string pic = "";
            pic = sortDirection == "ASC" ? "<img src='../Images/icon/arrowup.gif' />" : "<img src='../Images/icon/arrowdown.gif' />";

            foreach (DataGridColumn item in dgList.Columns)
            {
                if (item.SortExpression == sortExpression)
                {
                    item.HeaderText = item.FooterText + " " + pic;
                }
                else
                    item.HeaderText = item.FooterText;
            }

            this.BindGridView();

        }

        private void BindGridView()
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.dgList.Attributes["SortExpression"];
            string sortDirection = this.dgList.Attributes["SortDirection"];
            if (sortExpression != null)
            {
                // 调用业务数据获取方法
                string sort = string.Format("  order by lower({0})  {1} ", sortExpression, sortDirection);
                if (sortExpression == "uptime")
                {
                    sort = string.Format("  order by {0}  {1} ", sortExpression, sortDirection);
                }
                DataTable dtBind = GetDataSet(sort).Tables[0];
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                // GridView绑定并显示数据
                this.dgList.DataSource = GetPageTable(dtBind, AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                this.dgList.DataBind();
            }
            else
                btnSubmit_Click(null, null);
        }
    }
}